onconnect = function (event) {
    const port = event.ports[0]
    port.start()

    port.onmessage = (e) => {
        const { type, url, msg } = e.data || {}

        if (type === 'init' && url) {
            WebSocketUtil.createWebSocket(url, port)
        }

        if (type === 'sendMessage') {
            WebSocketUtil.sendMessage(msg)
        }

        if (type === 'close') {
            WebSocketUtil.closeSocket()
        }
    }
}

const WebSocketUtil = (function () {
    let url
    let Socket = null
    let isReconnecting = true
    let interval = null
    let _port = null

    function createWebSocket(socketUrl, port) {
        _port = port
        isReconnecting = true
        url = socketUrl
        try {
            Socket && Socket.close()
            Socket = new WebSocket(`${url}`)
            Socket.onopen = onopen
            Socket.onmessage = onmessage
            Socket.onerror = onerror
            Socket.onclose = onclose
        } catch (error) {
            console.error(error)
        }
    }

    function onopen() {
        sendPing({ heart: `heart` })
    }

    function onmessage(event) {
        // ✅ 正确地通过 port 发送消息给主线程
        _port && _port.postMessage(event.data)
    }

    function onerror(err) {
        console.error("websocket连接出错", err)
        Socket && Socket.close()
        clearInterval(interval)
        if (Socket && Socket.readyState !== Socket.CLOSED) {
            Socket = null
            createWebSocket(url, _port)
        }
    }

    function onclose() {
        console.error("websocket已关闭")
        clearInterval(interval)
        if (isReconnecting) {
            if (Socket && Socket.readyState !== Socket.CLOSING) {
                Socket = null
                createWebSocket(url, _port)
            }
        }
    }

    function sendPing(message) {
        clearInterval(interval)
        Socket && Socket.send(JSON.stringify(message))
        interval = setInterval(() => {
            Socket && Socket.send(JSON.stringify(message))
        }, 5000)
    }

    function sendMessage(msg) {
        setTimeout(() => {
            if (Socket.readyState == Socket.CONNECTING) {
                sendMessage(msg)
            } else {
                Socket.send(msg)
            }
        }, 1000)
    }

    function closeSocket() {
        clearInterval(interval)
        isReconnecting = false
        Socket && Socket.close()
        Socket = null
    }

    return {
        closeSocket,
        createWebSocket,
        sendMessage,
    }
})()
